package com.cskaoyan.service.admin.impl;

import com.aliyuncs.utils.StringUtils;
import com.cskaoyan.bean.*;
import com.cskaoyan.bean.param.BaseParam;
import com.cskaoyan.bean.param.CommonData;
import com.cskaoyan.bean.vo.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.service.admin.MarketGoodsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Can
 * @since 2022/06/26 15:18
 */
@Service
public class MarketGoodsServiceImpl implements MarketGoodsService {

    @Autowired
    MarketGoodsMapper marketGoodsMapper;

    @Autowired
    MarketBrandMapper marketBrandMapper;

    @Autowired
    MarketCategoryMapper marketCategoryMapper;

    @Autowired
    MarketGoodsAttributeMapper marketGoodsAttributeMapper;

    @Autowired
    MarketGoodsSpecificationMapper marketGoodsSpecificationMapper;

    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;

    /**
     * 获取商品列表
     * goodsSn 以及goodsId均是直接匹配
     * name是模糊查询
     * gallery 查询到的数据是String  但要求返回list 暂未解决
     *
     * @param baseParam
     * @return com.cskaoyan.bean.vo.BaseRespVo
     * @author Can
     * @since 2022/06/26 15:37
     */
    @Override
    public BaseRespVo getGoodsList(BaseParam baseParam, String goodsSn, String name, Integer goodsId) {
        // 查询未删除的商品
        MarketGoodsExample example = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria = example.createCriteria().andDeletedEqualTo(false);

        if (baseParam.getLimit() == 0) {
            PageHelper.startPage(0, 0);
            List<MarketGoods> marketGoods = marketGoodsMapper.selectByExampleWithBLOBs(example);
            PageInfo<MarketGoods> marketGoodsPageInfo = new PageInfo<>(marketGoods);
            return BaseRespVo.ok(CommonData.data(marketGoodsPageInfo));
        }

        // 排序
        example.setOrderByClause(baseParam.getSort() + " " + baseParam.getOrder());
        // 查询条件 名称模糊查询  id 和 编号 精确查询
        if (name != null && !name.equals("")) {
            String trim = name.trim();
            criteria.andNameLike("%" + trim + "%");
        }
        if (goodsSn != null && !goodsSn.equals("")) {
            criteria.andGoodsSnEqualTo(goodsSn);
        }
        if (goodsId != null && !goodsId.equals("")) {
            criteria.andIdEqualTo(goodsId);
        }

        PageHelper.startPage(baseParam.getPage(), baseParam.getLimit());
        List<MarketGoods> goodsList = marketGoodsMapper.selectByExampleWithBLOBs(example);

        BaseRespVo baseRespVo = new BaseRespVo();
        if (goodsList != null) {
            PageInfo<MarketGoods> pageInfo = new PageInfo<>(goodsList);

            CommonData commonData = CommonData.data(pageInfo);

            baseRespVo.setErrno(0);
            baseRespVo.setData(commonData);
            baseRespVo.setErrmsg("成功");
        } else {
            baseRespVo.setErrno(404);
            baseRespVo.setErrmsg("失败");
        }
        return baseRespVo;
    }

    /**
     * 此方法用于获取所有品牌和类别
     *
     * @return com.cskaoyan.bean.vo.BaseRespVo
     * @author Can
     * @since 2022/06/26 21:21
     */
    @Override
    public BaseRespVo getCatAndBrand() {
        List<InnerBrandOfCatAndBrandVO> brandList = marketBrandMapper.selectValueAndLabel();
        List<InnerCategoryOfCatAndBrandL1VO> categoryList = marketCategoryMapper.selectValueAndLabel();

        CatAndBrandVO catAndBrandVO = new CatAndBrandVO();
        catAndBrandVO.setBrandList(brandList);
        catAndBrandVO.setCategoryList(categoryList);

        BaseRespVo baseRespVo = BaseRespVo.ok(catAndBrandVO);
        return baseRespVo;
    }

    /**
     * 此方法用来添加商品 goods表 product表 specification表 attribute表
     *
     * @param marketGoodsBO
     * @return com.cskaoyan.bean.vo.BaseRespVo
     * @author Can
     * @since 2022/06/27 9:12
     */
    @Transactional
    @Override
    public BaseRespVo addGoods(MarketGoodsBO marketGoodsBO) {
        // 先插入market_goods表 获取自增的 goodsId  赋值给其他的对象 依次插入即可

        MarketGoods goods = marketGoodsBO.getGoods();

        // 判断商品名称 和 编号是否为空
        if (StringUtils.isEmpty(goods.getGoodsSn()) || StringUtils.isEmpty(goods.getName())) {
            BaseRespVo baseRespVo = new BaseRespVo();
            baseRespVo.setErrno(611);
            baseRespVo.setErrmsg("商品名称和编号不能为空");
            return baseRespVo;
        }

        List<MarketGoodsAttribute> attributes = marketGoodsBO.getAttributes();
        List<MarketGoodsProduct> products = marketGoodsBO.getProducts();
        List<MarketGoodsSpecification> specifications = marketGoodsBO.getSpecifications();

        // 判断是否重名
        MarketGoodsExample example = new MarketGoodsExample();
        example.createCriteria().andNameLike(goods.getName());
        List<MarketGoods> marketGoods = marketGoodsMapper.selectByExample(example);
        if (marketGoods.size() != 0) {
            BaseRespVo baseRespVo = new BaseRespVo();
            baseRespVo.setErrno(611);
            baseRespVo.setErrmsg("商品名已经存在");
            return baseRespVo;
        }

        // 判断参数是否正确
        if (goods.getCounterPrice() == null) {
            goods.setCounterPrice(BigDecimal.ZERO);
        }
        if (goods.getCounterPrice().compareTo(BigDecimal.ZERO) < 0) {
            BaseRespVo baseRespVo = new BaseRespVo();
            baseRespVo.setErrno(401);
            baseRespVo.setErrmsg("商品价格和数量必须非负数");
            return baseRespVo;
        }
        if (products.size() != 0) {
            for (MarketGoodsProduct product : products) {
                if (product.getPrice().compareTo(BigDecimal.ZERO) < 0 || product.getNumber().compareTo(0) < 0) {
                    BaseRespVo baseRespVo = new BaseRespVo();
                    baseRespVo.setErrno(401);
                    baseRespVo.setErrmsg("商品价格和数量必须非负数");
                    return baseRespVo;
                }
            }
        }

        // 添加商品
        goods.setRetailPrice(goods.getCounterPrice());
        if (products.size() != 0) {
            for (MarketGoodsProduct product : products) {
                if (goods.getRetailPrice().compareTo(product.getPrice()) > 0) {
                    goods.setRetailPrice(product.getPrice());
                }
            }
        }
        goods.setAddTime(new Date());
        goods.setUpdateTime(new Date());
        goods.setDeleted(false);
        goods.setSortOrder((short) 100);
        if (goods.getUnit() == null) {
            goods.setUnit("件");
        }
        if (goods.getCategoryId() == null) {
            goods.setCategoryId(0);
        }
        if (goods.getBrandId() == null) {
            goods.setBrandId(0);
        }
        int insertGoods = marketGoodsMapper.insert(goods);
        if (insertGoods == 0) {
            return BaseRespVo.invalidData("添加失败");
        }


        // 添加参数
        if (attributes.size() != 0) {
            for (MarketGoodsAttribute attribute : attributes) {
                attribute.setGoodsId(goods.getId());
                attribute.setAddTime(new Date());
                attribute.setUpdateTime(new Date());
                attribute.setDeleted(false);
            }
            int insertAttributes = marketGoodsAttributeMapper.insertAttributeList(attributes);
            if (insertAttributes == 0) {
                return BaseRespVo.invalidData("添加失败");
            }
        }

        // 添加产品
        if (products.size() != 0) {
            for (MarketGoodsProduct product : products) {
                product.setGoodsId(goods.getId());
                product.setAddTime(new Date());
                product.setUpdateTime(new Date());
                product.setDeleted(false);
            }
            int insertProducts = marketGoodsProductMapper.insertProductList(products);
            if (insertProducts == 0) {
                return BaseRespVo.invalidData("添加失败");
            }
        }

        // 添加规格
        if (specifications.size() != 0) {
            for (MarketGoodsSpecification specification : specifications) {
                specification.setGoodsId(goods.getId());
                specification.setAddTime(new Date());
                specification.setUpdateTime(new Date());
                specification.setDeleted(false);
            }
            int insertSpecifications = marketGoodsSpecificationMapper.insertSpecificationList(specifications);
            if (insertSpecifications == 0) {
                return BaseRespVo.invalidData("添加失败");
            }
        }
        return BaseRespVo.ok();
    }

    /**
     * 此方法用于获取 商品详情
     *
     * @param id
     * @return com.cskaoyan.bean.vo.BaseRespVo
     * @author Can
     * @since 2022/06/27 16:53
     */
    @Override
    public BaseRespVo getGoodsDetail(Integer id) {
        MarketGoods goods = marketGoodsMapper.selectByPrimaryKey(id);
        List<MarketGoodsAttribute> attributes = marketGoodsAttributeMapper.selectByGoodsId(id);
        List<MarketGoodsProduct> products = marketGoodsProductMapper.selectByGoodId(id);
        List<MarketGoodsSpecification> specifications = marketGoodsSpecificationMapper.selectByGoodsId(id);
        Integer categoryId = marketCategoryMapper.selectLevelOneId(goods.getCategoryId());
        Integer[] categoryIds = {categoryId, goods.getCategoryId()};

        MarketGoodsDetailVo detailVo = new MarketGoodsDetailVo();
        detailVo.setGoods(goods);
        detailVo.setAttributes(attributes);
        detailVo.setProducts(products);
        detailVo.setSpecifications(specifications);
        detailVo.setCategoryIds(categoryIds);

        return BaseRespVo.ok(detailVo);
    }

    /**
     * 此方法用于更新商品信息  goods表 product表 specification表 attribute表
     * goods表 product表 specification表 直接执行更新操作
     * attribute表 要判断 是不是 新添加的参数 其次要看deleted是否为true
     * 如果是新添加的参数且为true 则跳过，否则添加至表中，
     * 如果不是新添加的，false执行更新操作，true执行删除操作(伪删除)
     *
     * @param marketGoodsBO
     * @return com.cskaoyan.bean.vo.BaseRespVo
     * @author Can
     * @since 2022/06/27 19:07
     */
    @Transactional
    @Override
    public BaseRespVo updateGoods(MarketGoodsBO marketGoodsBO) {
        MarketGoods goods = marketGoodsBO.getGoods();
        List<MarketGoodsProduct> products = marketGoodsBO.getProducts();
        List<MarketGoodsSpecification> specifications = marketGoodsBO.getSpecifications();
        List<MarketGoodsAttribute> attributes = marketGoodsBO.getAttributes();

        // 判断重复 名字已修改但重复 不允许
        MarketGoodsExample example = new MarketGoodsExample();
        example.createCriteria().andNameLike(goods.getName()).andIdNotEqualTo(goods.getId());
        List<MarketGoods> marketGoods = marketGoodsMapper.selectByExample(example);
        if (marketGoods.size() != 0) {
            BaseRespVo baseRespVo = new BaseRespVo();
            baseRespVo.setErrno(611);
            baseRespVo.setErrmsg("商品名已经存在");
            return baseRespVo;
        }

        // 判断参数是否正确
        if (goods.getCounterPrice() == null) {
            goods.setCounterPrice(BigDecimal.ZERO);
        }
        if (goods.getCounterPrice().compareTo(BigDecimal.ZERO) < 0) {
            BaseRespVo baseRespVo = new BaseRespVo();
            baseRespVo.setErrno(401);
            baseRespVo.setErrmsg("商品价格和数量必须非负数");
            return baseRespVo;
        }
        if (products.size() != 0) {
            for (MarketGoodsProduct product : products) {
                if (product.getPrice().compareTo(BigDecimal.ZERO) < 0 || product.getNumber().compareTo(0) < 0) {
                    BaseRespVo baseRespVo = new BaseRespVo();
                    baseRespVo.setErrno(401);
                    baseRespVo.setErrmsg("商品价格和数量必须非负数");
                    return baseRespVo;
                }
            }
        }

        BigDecimal retailPrice = BigDecimal.valueOf(Double.MAX_VALUE);
        // 更新products表
        for (MarketGoodsProduct product : products) {
            if (retailPrice.compareTo(product.getPrice()) > 0) {
                retailPrice = product.getPrice();
            }
            product.setUpdateTime(new Date());
            marketGoodsProductMapper.updateByPrimaryKeySelective(product);
        }

        // 更新goods表
        goods.setUpdateTime(new Date());
        goods.setRetailPrice(retailPrice);
        marketGoodsMapper.updateByPrimaryKeyWithBLOBs(goods);

        // 更新specification表
        for (MarketGoodsSpecification specification : specifications) {
            specification.setUpdateTime(new Date());
            marketGoodsSpecificationMapper.updateByPrimaryKeySelective(specification);
        }

        // 更新attribute表
        ArrayList<MarketGoodsAttribute> attributeArrayList = new ArrayList<>();
        for (MarketGoodsAttribute attribute : attributes) {
            // 有id说明已在表中
            if (attribute.getId() != null) {
                // 将已有的参数真删除  就将下面代码放开
                // 如果删除标记为true 删除
                // if (attribute.getDeleted()) {
                //     marketGoodsAttributeMapper.deleteByPrimaryKey(attribute.getId());
                //     continue;
                // }
                // 删除标记为false 更新
                attribute.setUpdateTime(new Date());
                marketGoodsAttributeMapper.updateByPrimaryKeySelective(attribute);
                continue;
            }
            // 没有id 说明是新增加的参数
            // 删除标记为null则添加
            if (attribute.getDeleted() == null) {
                attribute.setGoodsId(goods.getId());
                attribute.setAddTime(new Date());
                attribute.setUpdateTime(new Date());
                attribute.setDeleted(false);
                attributeArrayList.add(attribute);
            }
        }
        if (attributeArrayList.size() != 0) {
            int insertAttributeList = marketGoodsAttributeMapper.insertAttributeList(attributeArrayList);
            if (insertAttributeList == 0) {
                return BaseRespVo.invalidData("更新失败");
            }
        }
        return BaseRespVo.ok();
    }

    /**
     * 用于删除商品
     *
     * @param marketGoods
     * @return com.cskaoyan.bean.vo.BaseRespVo
     * @author Can
     * @since 2022/06/27 21:01
     */
    @Transactional
    @Override
    public BaseRespVo deleteGoods(MarketGoods marketGoods) {
        int goodsId = marketGoods.getId();

        marketGoods.setDeleted(true);
        // 伪删除
        marketGoodsMapper.setDeleted(marketGoods);

        marketGoodsProductMapper.setDeleted(goodsId);

        marketGoodsAttributeMapper.setDeleted(goodsId);

        marketGoodsSpecificationMapper.setDeleted(goodsId);

        // 真删除
        // marketGoodsMapper.deleteByPrimaryKey(goodsId);
        // marketGoodsProductMapper.deleteProductsByGoodsId(goodsId);
        // marketGoodsSpecificationMapper.deleteSpecsByGoodsId(goodsId);
        // marketGoodsAttributeMapper.deleteAttributeBYGoodsId(goodsId);
        return BaseRespVo.ok();
    }
}
